<template>
  <div class="payment-manage">
    <!-- 搜索表单 -->
    <div class="search-wrap mt20 pd20">
      <SearchForm ref="searchFormRef" :list="[...formList]" @submit="search" @reset="reset"></SearchForm>
    </div>

    <!-- 全选、排序 -->
    <div class="middle-wrap jzt-flex-bt">
      <div class="jzt-flex-center">
        <el-checkbox
          class="select-circle select-all"
          v-model="selectAll"
          :disabled="companyList.length <= 0"
          :label="`全选搜索结果`"
          :indeterminate="indeterminate"
          @change="clickSelectAll"
        />
        <el-button type="primary" :disabled="checkList.length === 0" link @click="openEdit(checkList)">
          <p style="line-height: 32px">/ 批量设置（{{ checkList.length }}）</p>
        </el-button>
      </div>

      <div>
        <span class="f14">排序：</span>
        <el-button type="info" class="jzt-button f14" @click="clickSort">
          销量数据<el-icon :class="{ black: orderSort === 1 }" class="gray"><SortDown /></el-icon>
          <el-icon :class="{ black: orderSort === 2 }" class="gray" style="margin-left: -8px"><SortUp /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="list-wrap">
      <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
        <template v-if="companyList.length > 0">
          <div v-for="(item, index) in companyList" :key="index" class="list-item mb20">
            <div class="checkbox">
              <el-checkbox class="select-circle" label="" :value="item.factoryId"></el-checkbox>
            </div>
            <div class="card-content">
              <header class="jzt-flex-bt">
                <h1 class="f18">{{ item.factoryName || "-" }}</h1>
                <p class="f14">
                  销售数据金额：<span style="color: #ff3333">¥{{ item.payableTotalAmount }}</span>
                </p>
              </header>
              <div class="info-warap jzt-flex-bt pd20 f14">
                <p>老板-{{ item.bossName || "-" }}：{{ item.bossMobile || "-" }}</p>
                <p>跟单-{{ item.trackerName || "-" }}：{{ item.trackerTel || "-" }}</p>
                <p>账务对账人员-{{ item.financeReconciliationName || "-" }}：{{ item.financeReconciliationMobile || "-" }}</p>
                <p>入驻时间：{{ item.createTime || "-" }}</p>
              </div>
              <div class="table-header jzt-flex-bt pl20 pr20 mb14">
                <p class="f14">分期收款计划</p>
                <el-button type="primary" link @click="openEditOne([item.factoryId])">
                  编辑 <el-icon class="ml8"><Edit /></el-icon>
                </el-button>
              </div>
              <div class="table-body" v-if="item.collectionPlan.detailList?.length > 0">
                <div class="table-row" v-for="(item2, index2) in item.collectionPlan.detailList" :key="index2">
                  <p>{{ item2.collectionType }}期款项</p>
                  <p>商家付款节点：{{ getNodeName(item2.businessNode) }}</p>
                  <p>商家付款比例：{{ item2.collectionScale }}%</p>
                  <p>供应商收款节点：{{ getNodeName(item2.collectionNode) }}</p>
                  <p v-if="item2.collectionCycle > 0">{{ item2.collectionCycle }}（{{ item2.collectionCycle }}个自然日）</p>
                  <p v-else>平台支付时效：0（立即转款）</p>
                </div>
              </div>
              <el-empty v-else description="这里暂时什么都没有" :image-size="40"></el-empty>
            </div>
          </div>
        </template>
        <el-empty v-else description="这里暂时什么都没有"></el-empty>
      </el-checkbox-group>
    </div>

    <div class="pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 分期收款计划-批量修改-抽屉 -->
    <PlanDrawer v-model:isOpen="isOpenPlan" :optionInfo="optionInfoPlan" @cancelSelect="cancelSelect" @submitOk="getList" />

    <!-- 分期收款计划-单个修改-抽屉 -->
    <PlanDrawerOne v-model:isOpen="isOpenPlanOne" :factoryIds="_factoryIds" :optionInfo="optionInfoPlanOne" @submitOk="getList" />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { Edit } from "@element-plus/icons-vue";
import PlanDrawer from "./components/planDrawer.vue";
import PlanDrawerOne from "./components/planDrawerOne.vue";
import { pageList } from "@/api/system/payment";

const companyList = ref([]);
const selectAll = ref(false);
const indeterminate = ref(false);
const checkList = ref([]); //选中的公司ids
const formData = ref({ factoryName: "" });
const formList = ref([
  {
    label: "入驻时间",
    model: "outTime",
    type: "daterange",
    labelWidth: "70"
  },
  {
    label: "供应商名称",
    model: "factoryName",
    type: "input",
    labelWidth: "110"
  },
  {
    label: "供应商收款节点",
    model: "collectionNode",
    type: "select",
    labelWidth: "110",
    data: [
      { label: "接单付款", value: 1 },
      { label: "生产完成确认", value: 2 },
      { label: "已发货", value: 3 },
      { label: "入库完成", value: 4 },
      { label: "配送完成", value: 5 },
      { label: "安装完成", value: 6 }
    ]
  }
]);
const pagination = ref({
  page: 1,
  size: 5,
  sizes: [5, 10, 20, 30, 40, 50],
  total: 0
});
const isOpenPlan = ref(false);
const optionInfoPlan = ref({ type: "edit", editArr: [] });
const isOpenPlanOne = ref(false);
const optionInfoPlanOne = ref({ type: "edit", detail: {} });
const orderSort = ref(1); //1正序 2倒序，默认正序
const _factoryIds = ref({});

onMounted(() => {
  getList();
});

const clickSort = () => {
  orderSort.value = orderSort.value === 1 ? 2 : 1;
  getList();
};

//获取收款节点-中文
const getNodeName = type => {
  const arr = [
    { label: "接单付款", value: "1" },
    { label: "生产完成确认", value: "2" },
    { label: "已发货", value: "3" },
    { label: "入库完成", value: "4" },
    { label: "配送完成 ", value: "5" },
    { label: "安装完成", value: "6" }
  ];
  const obj = arr.find(item => item.value === type);
  return obj?.label || "--";
};

//打开分期收款计划弹窗-批量
const openEdit = factoryIds => {
  _factoryIds.value = factoryIds;
  isOpenPlan.value = true;
  const arr = companyList.value.filter(item => {
    return factoryIds.includes(item.factoryId);
  });
  optionInfoPlan.value.editArr = arr;
};
//打开分期收款计划弹窗-单个
const openEditOne = factoryIds => {
  _factoryIds.value = factoryIds;
  isOpenPlanOne.value = true;
  const obj = companyList.value.find(item => {
    return factoryIds.includes(item.factoryId);
  });
  optionInfoPlanOne.value.detail = { ...obj, _time: new Date() };
};

//收款计划弹窗-取消选中-回调
const cancelSelect = obj => {
  const arr = checkList.value.filter(id => id !== obj.factoryId);
  checkList.value = arr;

  handleCheckedChange(arr);
  openEdit(arr);
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    // 订单时间
    _form.startTime = form?.outTime ? form?.outTime[0] : null;
    _form.endTime = form?.outTime ? form?.outTime[1] : null;
    delete _form.outTime;
    formData.value = _form;
    // console.log("处理后的数据", formData.value);
  } else {
    formData.value = { factoryName: "" };
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
};

const getList = () => {
  pageList({
    ...formData.value,
    page: pagination.value.page,
    size: pagination.value.size,
    orderSort: orderSort.value
  }).then(res => {
    if (res.code === 200) {
      companyList.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
  checkList.value = []; //分页的时候，清空当前页的选中数据
  selectAll.value = false; //分页的时候，清空当前页的选中数据
  indeterminate.value = false; //分页的时候，清空当前页的选中数据
};

const clickSelectAll = val => {
  checkList.value = val ? companyList.value.map(item2 => item2.factoryId) : [];
  indeterminate.value = false;
};
/**
 *
 * @param 点击商品复选框
 */
const handleCheckedChange = value => {
  const checkedCount = value.length;
  selectAll.value = checkedCount === companyList.value.length;
  indeterminate.value = checkedCount > 0 && checkedCount < companyList.value.length;
};
</script>

<style lang="scss" scoped>
:deep(.el-date-editor.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}
:deep(.select-circle.el-checkbox) {
  .el-checkbox__inner {
    border-radius: 50% !important;
    transform: scale(1.5);
  }
  &.select-all {
    .el-checkbox__inner {
      transform: scale(1.2);
    }
  }
}
h1,
p {
  margin: 0;
  padding: 0;
}
.black {
  color: black !important;
}
.gray {
  color: rgba(4, 24, 48, 0.1);
}
.payment-manage {
  padding: 0 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
  .search-wrap {
    background-color: #f6f8fa;
  }

  .middle-wrap {
    border-bottom: 1px solid #e1e6ed;
    margin: 20px 0 20px 0;
    padding-bottom: 10px;
  }

  .list-wrap {
    .list-item {
      position: relative;
      .card-content {
        min-height: 200px;
        background: #f5f7fa;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #e1e6ed;
        padding-bottom: 20px;
        :deep(.el-empty) {
          padding: 0 0 10px 0;
        }
        header {
          line-height: 50px;
          border-bottom: 1px solid #e1e6ed;
          padding: 0 20px 0 50px;
        }
        .info-warap {
          line-height: 24px;
          color: #86909c;
        }
        .table-body {
          padding: 0 20px;
          .table-row {
            display: grid;
            grid-template-columns: 100px 1fr 1fr 1fr 1fr;
            padding: 14px 16px;
            background-color: white;
            margin-bottom: 4px;
            p {
              line-height: 22px;
              font-size: 14px;
              color: #606266;
            }
          }
        }
      }
      .checkbox {
        position: absolute;
        top: 10px;
        left: 20px;
      }
    }
    .el-checkbox-group {
      font-size: unset !important;
    }
  }
}
</style>
